/*
Simple Forum Auto Poster.
Copyright (C) 2011 Gianni Van Hoecke.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package gui.menu;

import domain.DomainController;
import domain.enums.View;
import domain.template.Template;
import domain.filter.ExtensionFileFilter;
import domain.settings.Settings;
import gui.template.TemplateManagerContainer;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.logging.Level;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import persistence.OpenBrowser;

/**
 *
 * @author Gianni Van Hoecke <gianni.vh@gmail.com>
 *
 * Used for generating the menu bar.
 */
public class MenuBar
{
    /**
     * @return The menu bar.
     */
    public static JMenuBar getMenuBar()
    {
        JMenuBar menuBar = new JMenuBar();

        JMenu       menuFile = new JMenu("File");
        menuBar.add(menuFile);

        /*
         * Save post
         * Open post
         * ---
         * Store post
         * ---
         * Forums
         *    -> Import
         *    -> Export
         * ---
         * Templates
         *    -> New template
         *    -> ---
         *    -> x
         *    -> y
         *    -> z
         * ---
         * Exit
         * 
         */

        {
            JMenuItem save = new JMenuItem("Save post");
            menuFile.add(save);
            save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
            save.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    JFileChooser fc = new JFileChooser(DomainController.getInstance().getLastSelectedFolder());
                    fc.setDialogTitle("Save to...");
                    fc.showSaveDialog(null);
                    File file = fc.getSelectedFile();

                    if(file != null)
                    {
                        DomainController.getInstance().savePostTo(file);
                        DomainController.getInstance().setLastSelectedFolder(file.getParentFile());
                        String msg = "Post saved to \"" + file.getAbsolutePath() + "\"";
                        JOptionPane.showMessageDialog(null, msg, "Saved", JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            });
        }
        
        {
            JMenuItem open = new JMenuItem("Open post");
            menuFile.add(open);
            open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
            open.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    JFileChooser fc = new JFileChooser(DomainController.getInstance().getLastSelectedFolder());
                    fc.setDialogTitle("Open...");
                    fc.showOpenDialog(null);
                    File file = fc.getSelectedFile();

                    if(file != null)
                    {
                        DomainController.getInstance().loadPost(file);
                        DomainController.getInstance().setLastSelectedFolder(file.getParentFile());
                        DomainController.getInstance().getLogger().log(Level.INFO, "Post loaded!");
                    }
                }
            });
        }

        menuFile.addSeparator();

        {
            JMenuItem store = new JMenuItem("Store post");
            menuFile.add(store);
            store.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | InputEvent.SHIFT_DOWN_MASK));
            store.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    DomainController.getInstance().storePost();
                }
            });
        }

        menuFile.addSeparator();

        {
            JMenu forums = new JMenu("Forums");
            menuFile.add(forums);
            {
                JMenuItem importForums = new JMenuItem("Import");
                forums.add(importForums);
                importForums.addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent evt)
                    {
                        JFileChooser fc = new JFileChooser(DomainController.getInstance().getLastSelectedFolder());
                        fc.setFileFilter(new ExtensionFileFilter("Extensible Markup Language files", new String[]{"XML"}));
                        fc.setDialogTitle("Import from...");
                        fc.showOpenDialog(null);
                        File file = fc.getSelectedFile();

                        if(file != null)
                        {
                            DomainController.getInstance().importForums(file);
                        }
                    }
                });
            }
            {
                JMenuItem exportForums = new JMenuItem("Export");
                forums.add(exportForums);
                exportForums.addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent evt)
                    {
                        JFileChooser fc = new JFileChooser(DomainController.getInstance().getLastSelectedFolder());
                        fc.setFileFilter(new ExtensionFileFilter("Extensible Markup Language files", new String[]{"XML"}));
                        fc.setDialogTitle("Export to...");
                        fc.showSaveDialog(null);
                        File file = fc.getSelectedFile();

                        if(file != null)
                        {
                            DomainController.getInstance().exportForums(file);
                        }
                    }
                });
            }
        }

        menuFile.addSeparator();

        JMenu menuTemplates = new JMenu("Templates");
        menuFile.add(menuTemplates);
        {
            JMenuItem newTemplate = new JMenuItem("Manage templates");
            menuTemplates.add(newTemplate);
            newTemplate.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    SwingUtilities.invokeLater(new Runnable()
                    {
                        public void run()
                        {
                            TemplateManagerContainer tmc = new TemplateManagerContainer();
                            tmc.setLocationRelativeTo(null);
                            tmc.setVisible(true);
                        }
                    });
                }
            });
        }
        
        ArrayList<Template> templates = DomainController.getInstance().getTemplates().getTemplates();
        if(templates.size() > 0)
        {
            menuTemplates.addSeparator();

            for(final Template template : templates)
            {
                {
                    JMenuItem templateItem = new JMenuItem(template.getName());
                    menuTemplates.add(templateItem);
                    templateItem.addActionListener(new ActionListener()
                    {
                        public void actionPerformed(ActionEvent evt)
                        {
                            DomainController.getInstance().loadTemplate(template);
                        }
                    });
                }
            }
        }

        menuFile.addSeparator();

        {
            JMenuItem exit = new JMenuItem("Exit");
            menuFile.add(exit);
            exit.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    System.exit(0);
                }
            });
        }

        
        JMenu       menuEdit = new JMenu("Edit");
        menuBar.add(menuEdit);

        /*
         * Undo
         * Redo
         * ---
         * Show posting errors
         */
        {
            JMenuItem undo = new JMenuItem("Undo");
            menuEdit.add(undo);
            undo.setEnabled(false);
            undo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
            DomainController.getInstance().setUndo(undo);
            undo.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    DomainController.getInstance().undo();
                }
            });
        }
        {
            JMenuItem redo = new JMenuItem("Redo");
            menuEdit.add(redo);
            redo.setEnabled(false);
            redo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
            DomainController.getInstance().setRedo(redo);
            redo.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    DomainController.getInstance().redo();
                }
            });
        }
        {
            menuEdit.add(new JSeparator());
        }
        {
            JMenuItem showPostingErrors = new JMenuItem("Show posting errors");
            menuEdit.add(showPostingErrors);
            showPostingErrors.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    DomainController.getInstance().showPostingErrors();
                }
            });
        }
        
        JMenu       menuTools = new JMenu("Tools");
        menuBar.add(menuTools);

        /*
         * Unlock history
         * ---
         * Get movie info
         * Get and insert movie poster
         * Upload and insert image
         */
        {
            JMenuItem unlock = new JMenuItem("Unlock history");
            menuTools.add(unlock);
            unlock.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    DomainController.getInstance().tempUnlock();
                }
            });
        }
        {
            menuTools.add(new JSeparator());
        }
        {
            JMenuItem getMovieInfo = new JMenuItem("Get movie info");
            menuTools.add(getMovieInfo);
            getMovieInfo.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    String movieName = JOptionPane.showInputDialog(null, "Please enter the title of the movie:", "Get movie info", JOptionPane.QUESTION_MESSAGE);

                    if(movieName != null && movieName.trim().length() > 0)
                        DomainController.getInstance().getMovieInfo(movieName);
                    else
                        DomainController.getInstance().getLogger().log(Level.WARNING, "Invalid movie name!");
                }
            });
        }
        {
            JMenuItem getMoviePoster = new JMenuItem("Get and insert movie poster");
            menuTools.add(getMoviePoster);
            getMoviePoster.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    String movieName = JOptionPane.showInputDialog(null, "Please enter the title of the movie:", "Get and insert movie poster", JOptionPane.QUESTION_MESSAGE);

                    if(movieName != null && movieName.trim().length() > 0)
                        DomainController.getInstance().getAndInsertMoviePoster(movieName);
                    else
                        DomainController.getInstance().getLogger().log(Level.WARNING, "Invalid movie name!");
                }
            });
        }
        {
            JMenuItem uploadImage = new JMenuItem("Upload and insert image");
            menuTools.add(uploadImage);
            uploadImage.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    FileFilter filter = new ExtensionFileFilter("Image files", new String[] { "JPG", "PNG", "BMP", "GIF" });

                    JFileChooser fileChooser = new JFileChooser(DomainController.getInstance().getLastSelectedFolder());
                    fileChooser.setDialogTitle("Please select your image");
                    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    fileChooser.setMultiSelectionEnabled(false);
                    
                    fileChooser.setFileFilter(filter);

                    int status = fileChooser.showOpenDialog(null);
                    
                    if (status == JFileChooser.APPROVE_OPTION)
                    {
                        File selectedFile = fileChooser.getSelectedFile();
                        DomainController.getInstance().setLastSelectedFolder(selectedFile.getParentFile());
                        DomainController.getInstance().uploadImage(selectedFile);
                    }
                }
            });
        }

        JMenu       menuView = new JMenu("View");
        menuBar.add(menuView);

        /*
         * View forum & queue panels
         * ---
         * Post
         * Settings
         * History
         * Log
         * About
         */
        {
            JCheckBoxMenuItem enableForumPanel = new JCheckBoxMenuItem("View forum & queue panels");
            enableForumPanel.setSelected(DomainController.getInstance().getForums().isViewUI());
            menuView.add(enableForumPanel);
            enableForumPanel.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    DomainController.getInstance().toggleForumPanel();
                }
            });
        }

        {
            menuView.add(new JSeparator());
        }

        {
            JMenuItem post = new JMenuItem("Post");
            menuView.add(post);
            post.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    DomainController.getInstance().changeViewTo(View.POST);
                }
            });
        }
        {
            JMenuItem settings = new JMenuItem("Settings");
            menuView.add(settings);
            settings.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    DomainController.getInstance().changeViewTo(View.SETTINGS);
                }
            });
        }
        {
            JMenuItem history = new JMenuItem("History");
            menuView.add(history);
            history.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    DomainController.getInstance().changeViewTo(View.HISTORY);
                }
            });
        }
        {
            JMenuItem log = new JMenuItem("Log");
            menuView.add(log);
            log.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                        DomainController.getInstance().changeViewTo(View.LOG);
                }
            });
        }
        {
            JMenuItem about = new JMenuItem("About");
            menuView.add(about);
            about.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    DomainController.getInstance().changeViewTo(View.ABOUT);
                }
            });
        }

        JMenu       menuHelp = new JMenu("Help");
        menuBar.add(menuHelp);

        /*
         * Tutorials
         * Check for updates
         * Donate
         */

        {
            JMenuItem tutorials = new JMenuItem("Tutorials");
            menuHelp.add(tutorials);
            tutorials.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    OpenBrowser.openURL(Settings.TUTORIAL_URL);
                }
            });
        }
        {
            JMenuItem updates = new JMenuItem("Check for updates");
            menuHelp.add(updates);
            updates.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    DomainController.getInstance().checkForUpdates();
                }
            });
        }
        {
            JMenuItem donate = new JMenuItem("Donate");
            menuHelp.add(donate);
            donate.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {
                    OpenBrowser.openURL(Settings.DONATE_URL);
                }
            });
        }

        return menuBar;
    }
}